package com.swt.gap.common.graph;

import com.swt.gap.common.constant.GraphDbConstant;
import com.swt.gap.common.NodeTypeEnum;
import com.swt.gap.model.entity.OntologyNodeProperty;
import com.swt.gap.model.vo.ontology.OntologyNodeVO;
import com.swt.gap.service.OntologyNodeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 请填写说明
 *
 * @author sx
 * @date 2020/7/24 11:54
 */
@Component
public class StartupRunnerCreateNeo4jIndex implements CommandLineRunner {
    private final OntologyNodeService ontologyNodeService;
    private final GraphProcessor graphProcessor;
    private final FulltextIndexCommon fulltextIndexCommon;

    public StartupRunnerCreateNeo4jIndex(OntologyNodeService ontologyNodeService,
                                         GraphProcessor graphProcessor,
                                         FulltextIndexCommon fulltextIndexCommon) {
        this.ontologyNodeService = ontologyNodeService;
        this.graphProcessor = graphProcessor;
        this.fulltextIndexCommon = fulltextIndexCommon;
    }
    @Override
    public void run(String... args) throws Exception {
        //必须先建第一级label的索引，否则会影响插入数据的label顺序
        for (NodeTypeEnum nodeTypeEnum : NodeTypeEnum.values()) {
            if (nodeTypeEnum != NodeTypeEnum.EXTERNAL) {
                graphProcessor.createIndex(nodeTypeEnum.getName(), GraphDbConstant.PROPERTY_KEY_ID);
                graphProcessor.createIndex(nodeTypeEnum.getName(), GraphDbConstant.PROPERTY_KEY_TASK_ID);
            }
        }

        List<OntologyNodeVO> ontologyNodes = ontologyNodeService.listAllOntologyNodeAndProperty();
        if (!CollectionUtils.isEmpty(ontologyNodes)) {
            ontologyNodes.forEach(ontologyNode -> {
                String[] labels = ontologyNode.getLabels().split(",");
                List<OntologyNodeProperty> ontologyNodeProperties = ontologyNode.getOntologyNodePropertyList();
                ontologyNodeProperties.forEach(ontologyNodeProperty -> {
                    graphProcessor.createIndex(labels[0], ontologyNodeProperty.getPropertyKey());
                    graphProcessor.createIndex(labels[1], ontologyNodeProperty.getPropertyKey());
                });
//            graphProcessor.createIndex(labels[1], GraphDbConstant.PROPERTY_KEY_TASK_ID);
//            graphProcessor.createIndex(labels[1], GraphDbConstant.PROPERTY_KEY_ID);
            });
            fulltextIndexCommon.updateFulltextIndexAll(ontologyNodes);
        }
    }

}
